<template>
  <!-- <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    wrapClassName="j-user-select-modal"
    @ok="handleSubmit"
    @cancel="close"
    style="top: 50px"
    cancelText="关闭"
  > -->
    <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px">
      <a-col :md="6" :sm="24">
        <a-card :bordered="false">
          <!--组织机构-->
          <a-directory-tree
            selectable
            :selectedKeys="selectedDepIds"
            :checkStrictly="true"
            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
            :treeData="departTree"
            :expandAction="false"
            :defaultExpandAll="true"
            @select="onDepSelect"
            :load-data="onLoadDepartment"
          />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <a-card :bordered="false">
          <a-spin :spinning="loading">  
            <div :style="{ borderBottom: '1px solid #E9E9E9' }"> 
              <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">
                全部
              </a-checkbox>
            </div>
            <a-checkbox-group @change="onChange" class="select-data-slot" v-model="checkedList" :options="plainOptions">
              <!-- <a-row>
              <a-col :span="3" v-for="obj in dataSource">
                <a-checkbox :value="obj.slotId"> {{ obj.slotId }} </a-checkbox>
              </a-col>
            </a-row> -->
            </a-checkbox-group>
            <!--槽号列表-->
            <!-- <a-table
            ref="table"
            :scroll="scrollTrigger"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
            :loading="loading"
            @change="handleTableChange">
          </a-table> -->
          </a-spin>
        </a-card>
      </a-col>
    </a-row>
  <!-- </j-modal> -->
</template>

<script>
import { pushIfNotExist, filterObj } from '@/utils/util'
import {
  queryWorkshopTreeList,
  getUserList,
  queryUserByDepId,
  getDataWorkshopList,
  getDataAreaList,
  getDataSlotList,
} from '@/api/api'
import { getAction } from '@/api/manage'

export default {
  name: 'JSelectUserByDepModal',
  components: {},
  props: ['modalWidth', 'multi', 'userIds', 'store', 'text'],
  data() {
    return {
      queryParam: {
        username: '',
      },
      columns: [
        {
          title: '槽号',
          align: 'center',
          dataIndex: 'slotId',
        },
        {
          title: '所属车间',
          align: 'center',
          dataIndex: 'workshopId_dictText',
        },
        {
          title: '所属工区',
          align: 'center',
          dataIndex: 'areaId_dictText',
        },
        {
          title: '槽状态',
          align: 'center',
          dataIndex: 'status_dictText',
        },
        {
          title: '槽类型',
          align: 'center',
          dataIndex: 'typeId_dictText',
        },
      ],
      scrollTrigger: {},
      dataSource: [],
      selectionRows: [],
      selectedRowKeys: [],
      selectUserRows: [],
      selectUserIds: [],
      title: '选择槽位',
      ipagination: {
        current: 1,
        pageSize: 9999,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      isorter: {
        column: 'slotId',
        order: 'asc',
      },
      selectedDepIds: [],
      departTree: [],
      visible: true,
      form: this.$form.createForm(this),
      loading: false,
      expandedKeys: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
      checkedList: [], // '2101  ','2102  '
      indeterminate: true,
      checkAll: false,
      plainOptions: [],
    }
  }, 
  computed: {
    // 计算属性的 getter
    getType: function () {
      return this.multi == true ? 'checkbox' : 'radio'
    },
  },
  watch: {
    userIds: {
      immediate: true,
      handler() {
        this.initUserNames()
      },
    },
  },
  created() {
    // 该方法触发屏幕自适应
    this.resetScreenSize()
    this.showModal()
    this.loadData() 
  },
  methods: {
    initUserNames() {
      return
      if (this.userIds) {
        // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
        let values = this.userIds.split(',') + ','
        let param = { [this.store]: values }
        getAction('/sys/user/getMultiUser', param).then((list) => {
          this.selectionRows = []
          let selectedRowKeys = []
          let textArray = []
          if (list && list.length > 0) {
            for (let user of list) {
              textArray.push(user[this.text])
              selectedRowKeys.push(user['id'])
              this.selectionRows.push(user)
            }
          }
          this.selectedRowKeys = selectedRowKeys
          this.$emit('initComp', textArray.join(','))
        })
      } else {
        // JSelectUserByDep组件bug issues/I16634
        this.$emit('initComp', '')
        // 前端用户选择单选无法置空的问题 #2610
        this.selectedRowKeys = []
      }
    },
    async loadData(arg) {
      var that = this
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams() //查询条件
      this.loading = true
      getAction('/dataSlot/dataSlot/list', params)
        .then((res) => {
          if (res.success) {
            that.plainOptions = []
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
            this.dataSource.forEach((element) => {
              that.plainOptions.push(element.slotId.trim())
            })
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 触发屏幕自适应
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
    showModal() {
      this.visible = true
      this.queryWorkshopTree()
      this.initUserNames()
      this.loadData()
      this.form.resetFields()
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      var selectTreeId = this.selectedDepIds.join(',')
      if (selectTreeId.indexOf('_') > -1) {
        param.workshopId = selectTreeId.split('_')[0]
        param.areaId = selectTreeId.split('_')[1]
      } else {
        if (selectTreeId != 'all') {
          param.workshopId = selectTreeId
        }
      }
      return filterObj(param)
    },
    getQueryField() {
      let str = 'id,'
      for (let a = 0; a < this.columns.length; a++) {
        str += ',' + this.columns[a].dataIndex
      }
      return str
    },
    searchReset(num) {
      let that = this
      that.selectedRowKeys = []
      that.selectUserIds = []
      that.selectedDepIds = []
      if (num !== 0) {
        that.queryParam = {}
        that.loadData(1)
      }
    },
    close() {
      this.searchReset(0)
      this.visible = false
    },
    setCheckedList(selectArray){
      this.checkedList = selectArray;
    },
    handleTableChange(pagination, filters, sorter) {
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleSubmit() {
      let that = this
      //this.getSelectUserRows()
      //that.$emit('ok', that.selectUserRows)
      that.$emit('ok', that.checkedList)
      that.searchReset(0)
      that.close()
    },
    //获取选择用户信息
    getSelectUserRows() {
      this.selectUserRows = []
      for (let row of this.selectionRows) {
        if (this.selectedRowKeys.includes(row.id)) {
          this.selectUserRows.push(row)
        }
      }
      this.selectUserIds = this.selectUserRows.map((row) => row.username).join(',')
    },
    // 点击树节点,筛选出对应的用户
    onDepSelect(selectedDepIds) {
      if (selectedDepIds[0] != null) {
        if (this.selectedDepIds[0] !== selectedDepIds[0]) {
          this.selectedDepIds = [selectedDepIds[0]]
        }
      }
      this.loadData(1)
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      selectionRows.forEach((row) => pushIfNotExist(this.selectionRows, row, 'id'))
    },
    onSearch() {
      this.loadData(1)
    },
    // 根据选择的id来查询用户信息
    initQueryUserByDepId(selectedDepIds) {
      this.loading = true
      return queryUserByDepId({ id: selectedDepIds.toString() })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result
            this.ipagination.total = res.result.length
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    queryWorkshopTree() {
      //update-begin-author:taoyan date:20211202 for: 异步加载部门树 https://github.com/jeecgboot/jeecg-boot/issues/3196
      this.expandedKeys = []
      this.departTree = [{ key: 'all', children: [], title: '全部', isLeaf: false }]
      getDataWorkshopList().then((res) => {
        if (res.success) {
          for (let i = 0; i < res.result.records.length; i++) {
            let temp = res.result.records[i]
            temp['title'] = temp.workshopName
            temp['key'] = temp.workshopId
            temp['children'] = []
            temp['isLeaf'] = false
            this.departTree[0].children.push(temp)
          }
        }
      })
    },
    onLoadDepartment(treeNode) {
      return new Promise((resolve) => {
        var workshopId = treeNode.dataRef.workshopId
        if (!workshopId) {
          resolve()
          return
        }
        getDataAreaList({ workshopId: workshopId }).then((res) => {
          if (res.success) {
            //判断chidlren是否为空，并修改isLeaf属性值
            if (res.result.records.length == 0) {
              treeNode.dataRef['isLeaf'] = true
              return
            } else {
              var children = []
              for (let i = 0; i < res.result.records.length; i++) {
                var item = res.result.records[i]
                item['title'] = item.areaName
                item['key'] = workshopId + '_' + item.areaId
                item['isLeaf'] = true
                children.push(item)
              }
              treeNode.dataRef['children'] = children
            }
          }
        })
        resolve()
      })
    },
    //update-end-author:taoyan date:20211202 for: 异步加载部门树 https://github.com/jeecgboot/jeecg-boot/issues/3196
    modalFormOk() {
      this.loadData()
    },
    onChange(checkedList) {
      this.indeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length
      this.checkAll = checkedList.length === this.plainOptions.length
      this.$emit('change',checkedList);
    },
    onCheckAllChange(e) {
      var that = this
      Object.assign(this, {
        checkedList: e.target.checked ? that.plainOptions : [],
        indeterminate: false,
        checkAll: e.target.checked,
      })
      that.$emit('change',that.checkedList);
    },
  },
}
</script>
